package com.future.lock.me.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ImageUtils;
import com.bumptech.glide.Glide;
import com.future.baselib.activity.BaseActivity;
import com.future.baselib.entity.MessageEvent;
import com.future.baselib.utils.CommonUtils;
import com.future.baselib.utils.DensityUtil;
import com.future.baselib.utils.EventBusUtil;
import com.future.baselib.utils.UserInfoSharePreference;
import com.future.baselib.view.ActionSheetDialog;
import com.future.baselib.view.CircleImageView;
import com.future.lock.R;
import com.future.lock.common.Constants;
import com.future.lock.common.MyApp;
import com.future.lock.common.RefreshDataUtils;
import com.future.lock.common.activity.MainActivity;
import com.future.lock.common.http.HttpUtils;
import com.future.lock.common.http.response.DefaultHttpResponse;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.io.File;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class UserInfoActivity extends BaseActivity {

    @BindView(R.id.iv_left)
    ImageView ivLeft;
    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.view_line)
    View viewLine;
    @BindView(R.id.layout_title)
    FrameLayout layoutTitle;
    @BindView(R.id.iv_person)
    CircleImageView ivPerson;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.iv_clear)
    ImageView ivClear;
    @BindView(R.id.layout)
    View layout;
    private String imageStr = "";

    @Override
    protected void initContentView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_user_info);
        ButterKnife.bind(this);
    }

    @Override
    protected void initView() {
        setTitle("个人信息");
        setTitleRight("保存", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                save();
            }
        });
        Glide.with(this)
                .load(MyApp.getUserInfo().head_imgurl)
//                .asBitmap()
//                .skipMemoryCache(false)
                .error(R.mipmap.ic_person_default)
                .dontAnimate()
                .into(ivPerson);
        etName.setText(MyApp.getUserInfo().nick_name);
        layout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (isKeyboardShown(etName.getRootView())){
                    ivClear.setVisibility(View.VISIBLE);
                }else{
                    ivClear.setVisibility(View.GONE);
                }
            }
        });
    }

    private boolean isKeyboardShown(View rootView) {
        final float SOFT_KEYBOARD_HEIGHT_DP_THRESHOLD = 128f;
        Rect r = new Rect();
        rootView.getWindowVisibleDisplayFrame(r);
        int heightDiff = rootView.getBottom() - r.bottom;
        return heightDiff > DensityUtil.dip2px(this,SOFT_KEYBOARD_HEIGHT_DP_THRESHOLD);
    }

    private void save() {
        String nickname = etName.getText().toString().trim();
        if (TextUtils.isEmpty(nickname)) {
            toast("昵称不能为空");
            return;
        }
        if (TextUtils.isEmpty(imageStr) && TextUtils.equals(MyApp.getUserInfo().nick_name,nickname)) {
            toast("无任何修改");
            return;
        }

        HttpUtils.getHttpApi().setUserInfo(MyApp.getUserToken(),nickname,imageStr).enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                DefaultHttpResponse defaultResponse = new DefaultHttpResponse();
                defaultResponse.parse(response.body());
                toast(defaultResponse.msg);
                if (defaultResponse.success == 1) {
                    setResult(0x123);
                    finish();
                }else{
                    if (defaultResponse.code == 112){
                        RefreshDataUtils.logout(mContext);
                    }
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                toast(t.getMessage());
            }
        });
    }

    @Override
    protected void initLogic() {

    }

    @Override
    protected void getBundleExtras(Bundle extras) {

    }

    @OnClick({R.id.layout_icon, R.id.tv_logout, R.id.iv_clear})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_icon://选择头像
                choosePic();
                break;
            case R.id.tv_logout://退出登录
                RefreshDataUtils.logout(this);
                break;
            case R.id.iv_clear://清空文本
                etName.setText("");
                break;
        }
    }


    private void choosePic() {
        ActionSheetDialog dialog = new ActionSheetDialog(this).builder()
                .addSheetItem("拍照", ActionSheetDialog.SheetItemColor.BLACK, which -> AndPermission.with(UserInfoActivity.this)
                        .permission(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .rationale((requestCode, rationale) -> toast("请前往设置-应用授权管理开启权限以启用此功能"))
                        .callback(new PermissionListener() {
                            @Override
                            public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                                picTyTakePhoto();
                            }

                            @Override
                            public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                                toast("请前往设置-应用授权管理开启权限以启用此功能");
                            }
                        })
                        .start())
                .addSheetItem("相册", ActionSheetDialog.SheetItemColor.BLACK, which -> pickPhoto())
                .setCancelable(true)
                .setTitle("选择照片来源");
        dialog.show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    //使用照相机拍照获取图片
    public static final int TAKE_PHOTO_CODE = 1;
    //使用相册中的图片
    public static final int SELECT_PIC_CODE = 2;
    //图片裁剪
    private static final int PHOTO_CROP_CODE = 3;
    //定义图片的Uri
    private Uri photoUri;
    //图片文件路径


    /**
     * 拍照获取图片
     */
    private void picTyTakePhoto() {
        File cameraFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                getResources().getString(R.string.app_name)+ System.currentTimeMillis() + ".jpg");
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.N) {
            photoUri = FileProvider.getUriForFile(this,"com.future.lock.fileprovider",cameraFile);
        }else{
            photoUri = Uri.fromFile(cameraFile);
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                .putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        startActivityForResult(
                intent,
                TAKE_PHOTO_CODE);
    }

    /***
     * 从相册中取图片
     */
    private void pickPhoto() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
        } else {
            intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, SELECT_PIC_CODE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            //从相册取图片，有些手机有异常情况，请注意
            if (requestCode == SELECT_PIC_CODE) {
                if (data !=null) {
                    Uri selectImage = data.getData();
                    if (selectImage !=null) {
                        startPhotoZoom(selectImage,PHOTO_CROP_CODE);
                    }
                }
            } else if (requestCode == TAKE_PHOTO_CODE) {
                if (photoUri != null) {
                    startPhotoZoom(photoUri, PHOTO_CROP_CODE);
                }
            } else if (requestCode == PHOTO_CROP_CODE) {
                Bundle extras = data.getExtras();
                Bitmap photo = extras.getParcelable("data");
                if (photo != null) {
                    //这里可以把图片进行上传到服务器操作
                    changeIcon(photo);
                }
            }
        }

    }

    @SuppressWarnings("unchecked")
    private void changeIcon(Bitmap photo) {//修改头像
        //网络请求
//        Glide.with(this).load(photo).asBitmap().into(ivPerson);
//        ImageUtils.save(photo, Constants.ICON_PATH, Bitmap.CompressFormat.JPEG,true);
//        new Timer().schedule(new TimerTask() {
//            @Override
//            public void run() {
//                runOnUiThread(() -> Glide.with(UserInfoActivity.this).load(Constants.ICON_PATH).into(ivPerson));
//            }
//        },500);
        Glide.with(this).load(ImageUtils.bitmap2Bytes(photo, Bitmap.CompressFormat.JPEG)).into(ivPerson);
        imageStr = CommonUtils.getImg(photo);
    }

    /**
     * @param
     * @description 裁剪图片
     * @author ldm
     * @time 2016/11/30 15:19
     */
    private void startPhotoZoom(Uri uri, int REQUE_CODE_CROP) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // 去黑边
        intent.putExtra("scale", true);
        intent.putExtra("scaleUpIfNeeded", true);
        // aspectX aspectY 是宽高的比例，根据自己情况修改
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高像素
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        //取消人脸识别功能
        intent.putExtra("noFaceDetection", true);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
//        设置返回的uri
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        //设置为不返回数据
        intent.putExtra("return-data", true);
        startActivityForResult(intent, REQUE_CODE_CROP);
    }
}
